package com.contactbook.web.server.service;

import java.util.HashSet;

import java.util.Set;

import com.contactbook.web.client.dto.GroupDTO;
import com.contactbook.web.client.service.GroupService;
import com.contactbook.web.server.dto.GroupDTOConverter;

import contactbook.model.Group;
import contactbook.service.GroupServiceInterface;

public class GroupServiceImpl implements GroupService {

	private GroupServiceInterface groupService;
	
	public GroupServiceImpl() {
		ServiceLocator sl = ServiceLocator.getInstance();
		groupService = sl.getGroupService();
	}

	@Override
	public GroupDTO add(GroupDTO groupDTO, String login, String password) {
		groupService.login(login, password);
		Group group = GroupDTOConverter.convertDTO(groupDTO, true);
		return GroupDTOConverter.convert(groupService.add(group), true);	
	}

	@Override
	public void delete(int groupId, String login, String password) {
		groupService.login(login, password);
		groupService.delete(groupId);
		groupService.logout();
	}

	@Override
	public GroupDTO getGroupById(int groupId, String login, String password) {
		groupService.login(login, password);
		Group group = groupService.getGroupById(groupId);
		groupService.logout();
		return GroupDTOConverter.convert(group, true);
	}

	@Override
	public GroupDTO getGroupByName(String name, String login, String password) {
		groupService.login(login, password);
		Group group = groupService.getGroupByName(name);
		groupService.logout();
		return GroupDTOConverter.convert(group, true);
	}

	@Override
	public Set<GroupDTO> getGroups(String login, String password) {
		groupService.login(login, password);
		Set<GroupDTO> groupsDTO = new HashSet<GroupDTO>();
		Set<Group> groups = groupService.getGroups();
		groupService.logout();
		for (Group group : groups) {
			groupsDTO.add(GroupDTOConverter.convert(group, true));
		}
		return groupsDTO;
	}

	@Override
	public boolean isLogged(String login, String password) {
		boolean isLogged = false;
		groupService.login(login, password);
		isLogged = groupService.isLogged();
		groupService.logout();
		return isLogged;
	}

	@Override
	public void login(String login, String password) {
		groupService.login(login, password);
	}

	@Override
	public void logout() {
		groupService.logout();
	}

	@Override
	public void update(GroupDTO group, String login, String password) {
		groupService.login(login, password);
		groupService.update(GroupDTOConverter.convertDTO(group, true));
		groupService.logout();
	}
}
